package org.zwy.gradetrack.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.zwy.gradetrack.entity.Role;
import org.zwy.gradetrack.mapper.RoleMapper;
import org.zwy.gradetrack.service.RoleService;
import org.zwy.gradetrack.service.RoleValidationService;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 角色服务实现类
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Autowired
    private RoleValidationService roleValidationService;

    /**
     * 分页查询角色列表
     */
    public Page<Role> pageRoles(Integer current, Integer size, String name) {
        LambdaQueryWrapper<Role> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(name != null, Role::getRoleName, name)
                .orderByDesc(Role::getCreateTime);
        return page(new Page<>(current, size), wrapper);
    }

    /**
     * 创建角色
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean createRole(Role role) {
        // 检查角色名是否已存在
        LambdaQueryWrapper<Role> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Role::getRoleName, role.getRoleName());
        if (count(wrapper) > 0) {
            throw new RuntimeException("角色名已存在");
        }

        // 设置创建和更新时间
        LocalDateTime now = LocalDateTime.now();
        role.setCreateTime(now);
        role.setUpdateTime(now);

        return save(role);
    }

    /**
     * 更新角色
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean updateRole(Role role) {
        // 检查角色是否存在
        if (!roleValidationService.validateRoleExists(role.getId())) {
            throw new RuntimeException("角色不存在");
        }

        // 检查角色名是否已存在
        LambdaQueryWrapper<Role> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Role::getRoleName, role.getRoleName())
                .ne(Role::getId, role.getId());
        if (count(wrapper) > 0) {
            throw new RuntimeException("角色名已存在");
        }

        // 设置更新时间
        role.setUpdateTime(LocalDateTime.now());

        return updateById(role);
    }

    /**
     * 删除角色
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteRole(Long id) {
        // 检查角色是否存在
        if (!roleValidationService.validateRoleExists(id)) {
            throw new RuntimeException("角色不存在");
        }

        // 检查是否有用户关联此角色
        if (roleValidationService.getUserRoles(id).size() > 0) {
            throw new RuntimeException("该角色下存在用户，无法删除");
        }

        return removeById(id);
    }

    /**
     * 获取角色详情
     */
    public Role getRole(Long id) {
        return roleValidationService.getRole(id);
    }

    /**
     * 获取所有角色
     */
    public List<Role> getAllRoles() {
        return list();
    }

    @Override
    public List<Role> getRolesByUserId(Long userId) {
        // 获取用户角色关联
        List<Long> roleIds = roleValidationService.getUserRoles(userId).stream()
                .map(userRole -> userRole.getRoleId())
                .collect(Collectors.toList());

        if (roleIds.isEmpty()) {
            return List.of();
        }

        // 获取角色列表
        return listByIds(roleIds);
    }
} 